package com.example.textview.PLC;

import android.util.Log;

import com.example.textview.util.HexDump;
import com.example.textview.util.TcpHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.example.textview.util.HexDump.hexStringToByteArray;

public class Mythread extends Thread{


    public List<Fx_Commend> fxcommends=new ArrayList<>();

    public List<Fx_Commend> fxcommends_Write=new ArrayList<>();

    public Map<String,Fx_Commend> readMap=new HashMap<>();

    public void ConnectPLC()
    {

      readMap.put("D600", new Fx_Commend("D600", "word", 50));
      readMap.put("D602", new Fx_Commend("D602", "float", 30));//1#干垃圾重量
         readMap.put("Y00", new Fx_Commend("Y00", "bool", 10));//1#窗口
        readMap.put("M502", new Fx_Commend("M502", "bool", 50));//定时开关

        TcpHelper.sharedCenter().connect("192.168.8.32", 5551);
        TcpHelper.sharedCenter().setReceivedCallback(new TcpHelper.OnReceiveCallbackBlock() {
            @Override
            public void callback(String receicedMessage) {

            }

            @Override
            public void callback(String receicedMessage, String adr) {

                String valueHex=null;


                if(adr.contains("D")&receicedMessage.contains("8100"))
                {

                    String dataType = readMap.get(adr).getDataType();

                    valueHex= receicedMessage.substring(4);

                    if(dataType == "float")
                    {

                        if(valueHex!=null){
                            if(valueHex.length()==8)
                            {
                                valueHex = valueHex.toUpperCase();
                                valueHex= ChangeData(valueHex);

                                double f = HexDump.hexString2Float(valueHex);

                                String  result = String.valueOf(f);
                                f = Float.parseFloat(result);
                                BigDecimal b = new BigDecimal(new Double(f));
                                double f1 = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
                                readMap.get(adr).setResult(f1);

                                Log.d("hex","Float:"+f1);

                            }

                        }
                    }
                    else if(dataType == "word")
                    {
                        if(valueHex!=null){
                            if(valueHex.length()==4)
                            {
                                valueHex = valueHex.toUpperCase();
                                valueHex= ChangeData(valueHex);

                                int parseInt = Integer.parseInt(valueHex, 16);
                                readMap.get(adr).setResult(parseInt);

                                Log.d("hex","parseInt:"+parseInt);

                            }

                        }

                    }



                }

                else if(receicedMessage.contains("8000")){

                    valueHex= receicedMessage.substring(4);
                    if(valueHex!=null){
                        boolean b = false;

                        if (valueHex.substring(0,1).equals("1"))
                            b = true;

                        readMap.get(adr).setResult(b);

                        Log.d("hex","bool:"+b);
                    }
                }

            }
        });
    }

    public void write(String adr , boolean value)
    {
        String status="0";
        if(value==false)
            status="0";
        else status="1";

        Fx_Commend commend=new Fx_Commend(adr,"bool");
        commend.setValueSet(status);
        fxcommends_Write.add(commend);

    }

    public void write(String adr , float value){

        Fx_Commend commend=new Fx_Commend(adr,"float");
        commend.setValueSet(value);
        fxcommends_Write.add(commend);
    }

    public void write(String adr , int value){

        Fx_Commend commend=new Fx_Commend(adr,"word");
        commend.setValueSet(value);
        fxcommends_Write.add(commend);
    }

   public void setConnectedCallback(TcpHelper.OnServerConnectedCallbackBlock onServerConnectedCallbackBlock )
   {
       TcpHelper.sharedCenter().setConnectedCallback(onServerConnectedCallbackBlock);

   }

    @Override
    public void run() {
        super.run();

        fx_tcp();



    }



    void fx_tcp()
    {
        int size = fxcommends.size();
        int i = 0;
        String ID=null;
        Set<String> keySet;
        keySet = readMap.keySet();
        Iterator<String> it = keySet.iterator();
        List<String> keys = new ArrayList<>();
        FX_TCP plcTCP=new FX_TCP();

        while (it.hasNext())
            keys.add(it.next());


        size = keys.size();

        while (true){

            //region 写
            int count = fxcommends_Write.size();
            if(count>0)
            {
                String dataType = fxcommends_Write.get(count - 1).getDataType();
                String adr = fxcommends_Write.get(count - 1).getAdr();
                if(this.readMap.containsKey(adr))
                {
                    this.readMap.get(adr).setWeight_current();
                }

                if (dataType == "bool") {

                    String value = fxcommends_Write.get(count - 1).getValueSet().toString();
                    // plc.writeBool(adr, value);

                    ID= plcTCP.writeBool(adr, value);
                    byte[] bytes = hexStringToByteArray(ID);
                    TcpHelper.sharedCenter().send(bytes,adr);
                    Log.d("hex", "bool:"+ID);
                }

                else if (dataType == "word") {
                    String str = fxcommends_Write.get(count - 1).getValueSet().toString();

                    short value = Short.parseShort(str);
                    // plc.writeWord(adr, value);

                    ID= plcTCP.writeWord(adr, value);
                    byte[] bytes = hexStringToByteArray(ID);
                    TcpHelper.sharedCenter().send(bytes,adr);
                    Log.d("hex", "word:"+ID);


                } else if (dataType == "float") {

                    String str = fxcommends_Write.get(count - 1).getValueSet().toString();

                    float value = 0;
                    value = Float.parseFloat(str);
                    // plc.writeFloat(adr, value);
                    // Log.d("data", "float" + value);

                    ID= plcTCP.writeFloat(adr, value);
                    Log.d("hex","float:"+ ID);
                    byte[] bytes = hexStringToByteArray(ID);
                    TcpHelper.sharedCenter().send(bytes,adr);
                }


                fxcommends_Write.remove(count - 1);

            }
            //endregion

            //region 读
            else{
                if (i < size){
                    String dataType = readMap.get(keys.get(i)).getDataType();
                    String adr = readMap.get(keys.get(i)).getAdr();
                    boolean ispermit=readMap.get(keys.get(i)).isPermit();

                    if( ispermit) {

                        if (dataType == "bool") {
                            ID=  plcTCP.readBool(adr,"01");
                        }
                        else if(dataType == "word"){

                            ID= plcTCP.readWord(adr, 1);

                        }
                        else if (dataType == "float"){
                            ID= plcTCP.readFloat(adr);

                        }


                        byte[] bytes = hexStringToByteArray(ID);
                        TcpHelper.sharedCenter().send(bytes,adr);
                    }
                    i++;
                }

                else
                {
                    i=0;
                }

            }
            //endregion

        }

    }



    String ChangeData(String valueHex)
    {

        StringBuilder sb = new StringBuilder();//构造一个StringBuilder对象
        for (int k = 0; k < valueHex.length()/2; k++) {

            sb.insert(0, valueHex.substring(k * 2, k * 2 + 2));
        }
        valueHex = sb.toString();

        return valueHex;
    }
}
